package org.xl.main.jsonx;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonToJavaConverter extends JFrame {
    private JTextArea jsonInputArea;
    private JTextArea javaOutputArea;
    private JTextField classNameField;
    
    public JsonToJavaConverter() {
        setTitle("JSON转Java代码工具");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLayout(null); // 使用绝对布局
        
        initUI();
        
        setLocationRelativeTo(null); // 居中显示
        setVisible(true);
    }

    private void initUI() {
        // JSON输入标签
        JLabel jsonLabel = new JLabel("JSON输入:");
        jsonLabel.setBounds(20, 20, 100, 25);
        add(jsonLabel);
        
        // 类名输入标签
        JLabel classNameLabel = new JLabel("类名:");
        classNameLabel.setBounds(20, 300, 100, 25);
        add(classNameLabel);
        
        classNameField = new JTextField("MyClass");
        classNameField.setBounds(70, 300, 150, 25);
        add(classNameField);
        
        // JSON输入区域
        jsonInputArea = new JTextArea();
        jsonInputArea.setLineWrap(true);
        JScrollPane jsonScrollPane = new JScrollPane(jsonInputArea);
        jsonScrollPane.setBounds(20, 50, 750, 200);
        add(jsonScrollPane);
        
        // 示例JSON按钮
        JButton exampleButton = new JButton("示例JSON");
        exampleButton.setBounds(240, 300, 120, 25);
        add(exampleButton);
        
        // 转换按钮
        JButton convertButton = new JButton("转换");
        convertButton.setBounds(370, 300, 80, 25);
        add(convertButton);
        
        // 清除按钮
        JButton clearButton = new JButton("清除");
        clearButton.setBounds(460, 300, 80, 25);
        add(clearButton);
        
        // Java输出标签
        JLabel javaLabel = new JLabel("Java输出:");
        javaLabel.setBounds(20, 340, 100, 25);
        add(javaLabel);
        
        // Java输出区域
        javaOutputArea = new JTextArea();
        javaOutputArea.setEditable(false);
        javaOutputArea.setLineWrap(true);
        JScrollPane javaScrollPane = new JScrollPane(javaOutputArea);
        javaScrollPane.setBounds(20, 370, 750, 180);
        add(javaScrollPane);
        
        // 复制按钮
        JButton copyButton = new JButton("复制代码");
        copyButton.setBounds(550, 300, 120, 25);
        add(copyButton);
        
        // 添加事件监听器
        exampleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jsonInputArea.setText("{\n  \"name\": \"John\",\n  \"age\": 30,\n  \"isStudent\": false,\n  \"hobbies\": [\"reading\", \"swimming\"],\n  \"address\": {\n    \"street\": \"123 Main St\",\n    \"city\": \"New York\"\n  }\n}");
            }
        });
        
        convertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                convertJsonToJava();
            }
        });
        
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jsonInputArea.setText("");
                javaOutputArea.setText("");
            }
        });
        
        copyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String javaCode = javaOutputArea.getText();
                if (!javaCode.isEmpty()) {
                    Toolkit.getDefaultToolkit().getSystemClipboard()
                            .setContents(new java.awt.datatransfer.StringSelection(javaCode), null);
                    JOptionPane.showMessageDialog(JsonToJavaConverter.this, 
                            "已复制到剪贴板");
                }
            }
        });
    }
    
    private void convertJsonToJava() {
        String json = jsonInputArea.getText().trim();
        String className = classNameField.getText().trim();
        
        if (json.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入JSON数据");
            return;
        }
        
        if (className.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入类名");
            return;
        }
        
        try {
            String javaCode = generateJavaCode(json, className);
            javaOutputArea.setText(javaCode);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "JSON格式错误: " + ex.getMessage());
        }
    }
    
    private String generateJavaCode(String json, String className) {
        // 移除空格和换行符以简化处理
        String cleanedJson = json.replaceAll("\\s", "");
        
        // 检查JSON格式
        if (!cleanedJson.startsWith("{") || !cleanedJson.endsWith("}")) {
            throw new IllegalArgumentException("JSON应该是一个对象");
        }
        
        // 提取内容
        String content = cleanedJson.substring(1, cleanedJson.length() - 1);
        String regex = "\\{.*\\}";
        String regex2 = "\\[.*\\]";
        content = content.replaceAll(regex, "{}").replaceAll(regex2, "[]");
        if (content.isEmpty()) {
            return "public class " + className + " {\n    // 空类\n}";
        }
        
        StringBuilder javaCode = new StringBuilder();
        javaCode.append("import java.util.List;\n");
        javaCode.append("import java.util.ArrayList;\n\n");
        javaCode.append("public class ").append(className).append(" {\n");
        
        // 分割键值对
        String[] pairs = content.split(",");
        for (int i = 0; i < pairs.length; i++) {
            String pair = pairs[i];
            if (pair.isEmpty()) continue;
            String[] keyValue = pair.split(":", 2);
            if (keyValue.length != 2) continue;
            String key = keyValue[0].replaceAll("\"", "").trim();
            String value = keyValue[1].trim();
            
            // 确定字段类型
            String fieldType = determineType(value);
            String fieldName = toCamelCase(key);
            
            // 添加字段声明
            javaCode.append("    private ").append(fieldType).append(" ").append(fieldName).append(";\n");
        }
        
        javaCode.append("\n");
        
        // 生成getter和setter方法
        for (String pair : pairs) {
            if (pair.isEmpty()) continue;
            
            String[] keyValue = pair.split(":", 2);
            if (keyValue.length != 2) continue;
            
            String key = keyValue[0].replaceAll("\"", "").trim();
            String value = keyValue[1].trim();
            
            String fieldType = determineType(value);
            String fieldName = toCamelCase(key);
            String methodSuffix = capitalize(fieldName);
            
            // 生成getter方法
            javaCode.append("    public ").append(fieldType).append(" get").append(methodSuffix).append("() {\n");
            javaCode.append("        return this.").append(fieldName).append(";\n");
            javaCode.append("    }\n\n");
            
            // 生成setter方法
            javaCode.append("    public void set").append(methodSuffix).append("(").append(fieldType).append(" ").append(fieldName).append(") {\n");
            javaCode.append("        this.").append(fieldName).append(" = ").append(fieldName).append(";\n");
            javaCode.append("    }\n\n");
        }
        
        javaCode.append("}");
        return javaCode.toString();
    }
    
    private String determineType(String value) {
        if (value.startsWith("\"") && value.endsWith("\"")) {
            return "String";
        } else if (value.equals("true") || value.equals("false")) {
            return "boolean";
        } else if (value.matches("-?\\d+")) {
            return "int";
        } else if (value.matches("-?\\d+\\.\\d+")) {
            return "double";
        } else if (value.startsWith("[") && value.endsWith("]")) {
            // 简单处理数组类型
            if (value.length() > 2) {
                String element = value.substring(1, value.length() - 1).split(",")[0].trim();
                String elementType = determineType(element);
                return "List<" + elementType + ">";
            }
            return "List<Object>";
        } else if (value.startsWith("{") && value.endsWith("}")) {
            // 嵌套对象
            return "Object";
        }
        return "Object";
    }
    
    private String toCamelCase(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        // 将下划线或连字符命名转换为驼峰命名
        String[] parts = str.split("[_\\-]");
        StringBuilder result = new StringBuilder(parts[0]);
        
        for (int i = 1; i < parts.length; i++) {
            result.append(capitalize(parts[i]));
        }
        
        return result.toString();
    }
    
    private String capitalize(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    
    public static void main(String[] args) {
        // 使用SwingUtilities确保线程安全
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JsonToJavaConverter();
            }
        });
    }
}